/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ym.uiautomator2;

import android.os.HandlerThread;

public class UiAutomatorRunner {

	private static final String HANDLER_THREAD_NAME = "UiAutomatorRunnerThread";

	public static UiAutomatorRunner getInstance() {
		if (instance == null) {
			synchronized (mLock) {
				if (instance == null) {
					instance = new UiAutomatorRunner();
				}
			}
		}
		return instance;
	}
	private HandlerThread mHandlerThread;

	private UiAutomationShellWrapper mAutomationWrapper;

	private static UiAutomatorRunner instance;

	static final Object mLock = new Object();

	private UiAutomatorRunner() {
	}

	public UiAutomationShellWrapper getAutomationWrapper() {
		return mAutomationWrapper;
	}

	public synchronized void init(UiDevice device) {
		if (mHandlerThread != null) {
			return;
		}
		mHandlerThread = new HandlerThread(HANDLER_THREAD_NAME);
		mHandlerThread.setDaemon(true);
		mHandlerThread.start();
		mAutomationWrapper = new UiAutomationShellWrapper();
		mAutomationWrapper.connect();
		mAutomationWrapper.setRunAsMonkey(true);
		device.initialize(new ShellUiAutomatorBridge(mAutomationWrapper
				.getUiAutomation()));
	}

	public synchronized void uninit() {
		if (mHandlerThread == null) {
			return;
		}
		mAutomationWrapper.disconnect();
		mAutomationWrapper.setRunAsMonkey(false);
		mHandlerThread.quit();
		mHandlerThread = null;
		mAutomationWrapper = null;
	}
}
